<?php
include($_SERVER["DOCUMENT_ROOT"] . "/fonctions_globales.php");

class PHWServices { //TODO : remplacer les "SELECT *" par des champs plus précis.

    function __construct() {
        include($_SERVER["DOCUMENT_ROOT"] . "/bob.php");
        $this->mysqli = new_mysqli($host, $user, $password, $database); //connection à la DB
    }

    var $mysqli;

    /** Return a tab with data of gamer, which user_id = $idj */
    public function returnDataJoueur($idj, $want_pref_map_conquete) {
        if (get_num($idj) <= 0)
            return NULL;
        $query = "SELECT user_id, user_titre, username, couleur, nb_territoires, game_level, faction, clan, user_avatar, user_avatar_min";
        if ($want_pref_map_conquete == true)
            $query.= ", prefs_maps_conquete";
        $result = mysqli_query_with_error($this->mysqli, $query . " FROM gens WHERE user_id='$idj' LIMIT 1");
        return $result->fetch_assoc();
    }

    /** Return a tab with data of gamer, which user_id = $idj */
    public function getTitreNClan($numj, $id_titre, $id_clan) {
        $infos = Array();
        $infos['numj'] = $numj;
        $infos['titre'] = get_data_in_db($this->mysqli, "titres", "titre_id", $id_titre, "titre_name");
        $infos['clan'] = NULL; //TODO n'existe pas encore.
        return $infos;
    }

    /** Return a tab with contacts of gamer, which user_id = $idj */
    public function returnContactsJoueur($idj, $mdp) {
        if (get_num($idj) == 0  || $mdp != substr(get_data_in_db($this->mysqli, "gens", "user_id", $idj, "user_password"), 0, 20))
            return NULL;
        $result = mysqli_query_with_error($this->mysqli, "SELECT contact_id FROM gens_contact WHERE user_id='" . get_num($idj) . "'");
        $contacts = Array();
        while ($ligne = $result->fetch_assoc())
            $contacts[] = $ligne;
        return $contacts;
    }

    /** Return a tab with preferences of gamer, which user_id = $idj */
    public function returnPrefJoueur($idj, $mdp) {
        if (get_num($idj) == 0 || $mdp != substr(get_data_in_db($this->mysqli, "gens", "user_id", $idj, "user_password"), 0, 20))
            return NULL;
        return get_line_in_db($this->mysqli, "preference_ingame", "user_id", $idj);
    }

    /** Udpate preferences of gamer, which user_id = $idj */
    public function updatePrefsJoueur($idj, $list_pref, $mdp) {
        if (empty($list_pref) || get_num($idj) == 0 || $mdp != substr(get_data_in_db($this->mysqli, "gens", "user_id", $idj, "user_password"), 0, 20))
            return;
        $query = "UPDATE preference_ingame SET ";
        foreach ($list_pref as $clef => $valeur) {
            $query = $query . get_alphanumpoint($clef) . " = " . get_alphanumpoint($valeur) . ", ";
        }
        $query = substr($query, 0, strlen($query) - 2); //Supprime la dernière virgule.
        $query = $query . " WHERE user_id = " . get_num($idj);
        mysqli_query_with_error($this->mysqli, $query);
    }
    
    /** Udpate current_tuto of gamer, which user_id = $idj */
    public function updateCurrentTuto($idj, $num_tuto, $mdp) {
        if (get_num($num_tuto) == 0 || get_num($idj) == 0 || $mdp != substr(get_data_in_db($this->mysqli, "gens", "user_id", $idj, "user_password"), 0, 20))
            return false;
        $gains = Array();
        if($num_tuto == 3){//Il n'y a que trois tutos, changer ce nombre si ça change.
            if(get_data_in_db($this->mysqli, "gens_progression", "user_id", $idj, "current_tuto") >= 3)
                    return "deja_eu"; //Le joueur a déjà quitté le tuto, il ne doit pas y récuperer des gains !
            $gains['xp'] = 48;
            $gains['posthunes'] = 90;
            $gains['pt_chahut'] = 3;
            mysqli_query_with_error($this->mysqli, "UPDATE gens SET experience = {$gains['xp']}, posthunes = {$gains['posthunes']}, pt_chahut = {$gains['pt_chahut']} WHERE user_id = '$idj'"); //TODO si on modifie ces valeurs, les modifier aussi dans le flash. D'ailleurs des variables seraient surement plus propre (mais attention à la sécurité).
            $id_titre = 1; //Le titre de sortie d'entrainement.
            $deja_titre = mysqli_query_with_error($this->mysqli, "SELECT COUNT(*) as count FROM titres_debloques WHERE user_id='$idj' AND titre_id = $id_titre;")->fetch_assoc();
            if($deja_titre['count'] == 0){
                mysqli_query_with_error($this->mysqli, "INSERT INTO titres_debloques (user_id, titre_id) VALUES ($idj, $id_titre)"); //On débloque le titre début entrainement.
                $gains['titre'] = get_data_in_db($this->mysqli, "titres", "titre_id", $id_titre, "titre_name");
            }
        }
        $query = "UPDATE gens_progression SET current_tuto = '$num_tuto' WHERE user_id = '$idj'";
        mysqli_query_with_error($this->mysqli, $query);
        return $gains;
    }
    
    /** Udpate after_tuto of gamer, which user_id = $idj */
    public function updateProgressionAfterTuto($idj, $num_etape, $mdp) {
        if (get_num($idj) == 0 || get_num($num_etape) <= get_data_in_db($this->mysqli, "gens_progression", "user_id", $idj, "after_tuto") || $mdp != substr(get_data_in_db($this->mysqli, "gens", "user_id", $idj, "user_password"), 0, 20))
            return false;
        $query = "UPDATE gens_progression SET after_tuto = '$num_etape' WHERE user_id = '$idj'";
        mysqli_query_with_error($this->mysqli, $query);
        return true;
    }
    /** Udpate a secondary field of gens_progression of gamer, which user_id = $idj */
    public function SaveCloseBulles($idj, $fenetre, $mdp) {
        if(get_num($idj) == 0 || ($fenetre != "bulles_hot_seat" && $fenetre != "bulles_plibre" && $fenetre != "bulles_salle_attente") || $mdp != substr(get_data_in_db($this->mysqli, "gens", "user_id", $idj, "user_password"), 0, 20))
            return false;
        mysqli_query_with_error($this->mysqli, "UPDATE gens_progression SET $fenetre = 1 WHERE user_id = '$idj'");
        return true;
    }

    /** Return number of conquest win, which user_id = $idj */
    public function getNumGamesConquete($idj) {
        if (get_num($idj) == 0)
            return 0;
        $result = mysqli_query_with_error($this->mysqli, "SELECT COUNT(*) as count FROM games_ended WHERE (id_gagnant='$idj' OR id_perdant='$idj') AND conquete = 1 AND type_defaite < 10 AND type_defaite != 5;")->fetch_assoc();
	return $result['count'];
    }

    /** Udpate faction of gamer, which user_id = $idj */
    public function updateFaction($idj, $faction, $mdp) {
        if (get_num($idj) == 0 || get_alphanum($faction) == "" || get_data_in_db($this->mysqli, "gens", "user_id", $idj, "out_training") != 0  || $mdp != substr(get_data_in_db($this->mysqli, "gens", "user_id", $idj, "user_password"), 0, 20))
            return "Non";
        
        $gains = Array();
        $gains['territoires'] = 10;
        $id_portrait = (($faction == "wraak") ? 3 : (($faction == "rpatch") ? 4 : 2));
        $id_titre = 2;
        
        $query = "UPDATE gens SET faction = '$faction', out_training = '1', nb_territoires = '{$gains['territoires']}' WHERE user_id = '$idj'";
        mysqli_query_with_error($this->mysqli, $query);
        $deja_titre = mysqli_query_with_error($this->mysqli, "SELECT COUNT(*) as count FROM titres_debloques WHERE user_id='$idj' AND titre_id = $id_titre;")->fetch_assoc();
        if($deja_titre['count'] == 0)
            mysqli_query_with_error($this->mysqli, "INSERT INTO titres_debloques (user_id, titre_id) VALUES ($idj, $id_titre)"); //On débloque le titre post entrainement.
        $gains['titre'] = get_data_in_db($this->mysqli, "titres", "titre_id", $id_titre, "titre_name");
        
        $deja_portrait = mysqli_query_with_error($this->mysqli, "SELECT COUNT(*) as count FROM portraits_debloques WHERE user_id='$idj' AND portrait_id = '$id_portrait';")->fetch_assoc();
        if($deja_portrait['count'] == 0)
            mysqli_query_with_error($this->mysqli, "INSERT INTO portraits_debloques(user_id, portrait_id) VALUES($idj, $id_portrait);");
        $gains['portrait'] = get_data_in_db($this->mysqli, "portraits", "id", $id_portrait, "chemin");
        return $gains;
    }

    /** Return a tab with presets of gamer, which user_id = $idj */
    public function returnPresetsArmee($idj, $mdp) {
        if (get_num($idj) == 0 || $mdp != substr(get_data_in_db($this->mysqli, "gens", "user_id", $idj, "user_password"), 0, 20))
            return NULL;
        $result = mysqli_query_with_error($this->mysqli, "SELECT * FROM presets_armee WHERE joueur='" . get_num($idj) . "'");
        $presets = Array();
        while ($ligne = $result->fetch_assoc())
            $presets[] = $ligne;
        return $presets;
    }

    /** Save a preset */
    public function savePresetArmee($idj, $nom, $units, $faction, $mdp) {
        if (get_num($idj) == 0|| get_alphanum($faction) == "" || !preg_match("#^[a-zA-Z0-9_ -]+$#", $nom) || $mdp != substr(get_data_in_db($this->mysqli, "gens", "user_id", $idj, "user_password"), 0, 20))
            return null;
        $units = $this->mysqli->real_escape_string($units);
        $nom = $this->mysqli->real_escape_string($nom);
        mysqli_query_with_error($this->mysqli, "INSERT INTO presets_armee (joueur, name, unites, faction) VALUES ($idj, '$nom', '$units', '$faction')");
        $result = mysqli_query_with_error($this->mysqli, "SELECT * FROM presets_armee WHERE joueur=$idj && name='$nom' && faction='$faction' ORDER BY ID DESC LIMIT 1");
        return $result->fetch_assoc();
    }

    /** Update a preset */
    public function upPresetArmee($idj, $idpreset, $units, $faction, $mdp) {
        if (get_num($idj) == 0 || get_num($idpreset) == 0 || get_alphanum($faction) == "" || $mdp != substr(get_data_in_db($this->mysqli, "gens", "user_id", $idj, "user_password"), 0, 20))
            return null;
        $units = $this->mysqli->real_escape_string($units);
        mysqli_query_with_error($this->mysqli, "UPDATE presets_armee SET unites='$units', faction='$faction' WHERE ID=$idpreset && joueur=$idj");
        $result = mysqli_query_with_error($this->mysqli, "SELECT * FROM presets_armee WHERE joueur=$idj && ID=$idpreset");
        return $result->fetch_assoc();
    }

    /** Suppr a preset */
    public function supprPresetArmee($idj, $idpreset, $mdp) {
        if (get_num($idj) == 0 || get_num($idpreset) == 0 || $mdp != substr(get_data_in_db($this->mysqli, "gens", "user_id", $idj, "user_password"), 0, 20))
            return null;
        mysqli_query_with_error($this->mysqli, "DELETE FROM presets_armee WHERE ID=$idpreset && joueur=$idj");
        return "Y";
    }

    /** Save a game to review TODO sécuriser avec chépaquoi, pour pas surcharger la db */
    public function saveGameReview($online, $game_id, $joueurs, $factions, $id_map, $ressource, $gagnant, $date, $duree, $type_defaite, $ordres) {
        if (get_num($date) == 0 || get_num($duree) == 0 || get_num($id_map) == 0 || get_num($ressource) == 0)
            return null;
        $online = get_num($online);
        $game_id = $this->mysqli->real_escape_string($game_id);
        /*if($online == 1 && get_line_numbers($this->mysqli, "game_saved", "game_id", $game_id) != 0)
                return "Game allready saved";*/
        $joueurs = $this->mysqli->real_escape_string($joueurs);
        $gagnant = $this->mysqli->real_escape_string($gagnant);
        $factions = $this->mysqli->real_escape_string($factions);
        $type_defaite = $this->mysqli->real_escape_string($type_defaite);
        $ordres = $this->mysqli->real_escape_string($ordres);
        mysqli_query_with_error($this->mysqli, "INSERT INTO game_saved (online, game_id, joueurs, id_enregistreur, factions, id_map, ressource, gagnant, date, duree, type_defaite, ordres) VALUES 
			('$online', '$game_id', '$joueurs', '".get_num($_SESSION['id'])."', '$factions', '$id_map', $ressource, '$gagnant', '$date', '$duree', '$type_defaite', '$ordres')");
    }

    /** Return a saved game */
    public function returnGameReview($id_save) {
        return get_line_in_db($this->mysqli, "game_saved", "ID", $id_save);
    }

    /** Return a tab with infos of all maps */
    public function returnInfosMaps() {
        $result = mysqli_query_with_error($this->mysqli, "SELECT * FROM maps_infos ORDER BY taille");
        $maps = Array();
        while ($ligne = $result->fetch_assoc())
            $maps[] = $ligne;
        return $maps;
    }

    /** Return contenu of a map */
    public function returnMapContenu($idmap) {
        $contenu_map = get_line_in_db($this->mysqli, "maps_contenu", "id", get_num($idmap));
        return $contenu_map['contenu'];
    }

    /** Modifie a existant map TODO : à protéger en vérifiant si l'utilisateur est habilité à la modifier (et vérifier l'utilisateur) */
    public function modifieMap($idmap, $univers, $taille, $contenu) {
        if (get_num($idmap) == 0 || get_num($taille) == 0 || get_alphanum($univers) == "")
            return false;
        $is_officielle = get_data_in_db($this->mysqli, "maps_infos", "id", $idmap, "officielle");
        //La carte n'existe pas, ou on ne peut pas modifier les maps officielles.
        if ($is_officielle === NULL || $is_officielle == 1)
            return false;
        $contenu = $this->mysqli->real_escape_string($contenu);
        mysqli_query_with_error($this->mysqli, "UPDATE maps_infos SET univers='$univers', taille='$taille' WHERE id=$idmap");
        mysqli_query_with_error($this->mysqli, "UPDATE maps_contenu SET contenu='$contenu' WHERE id=$idmap");
        return true;
    }

    /** Save a new Map TODO : à protéger en vérifiant si l'utilisateur est habilité (pour pas surcharger la db) (et vérifier l'utilisateur) */
    public function saveNewMap($nom, $univers, $taille, $contenu) {
        if (get_num($taille) == 0 || get_alphanum($univers) == "")
            return "error in parameters";
        $nom = $this->mysqli->real_escape_string($nom);
        $contenu = $this->mysqli->real_escape_string($contenu);
        if (get_line_numbers($this->mysqli, "maps_infos", "nom", $nom) != 0)
            return "exist";
        mysqli_query_with_error($this->mysqli, "INSERT INTO maps_infos (nom, univers, taille) VALUES ('$nom', '$univers', '$taille')");
        $id = get_data_in_db($this->mysqli, "maps_infos", "nom", $nom, "id");
        mysqli_query_with_error($this->mysqli, "INSERT INTO maps_contenu (id, contenu) VALUES ('$id', '$contenu')");
        return "ok" . $id;
    }

    /** Supprime une map TODO : à protéger en vérifiant si l'utilisateur est habilité à la modifier (et vérifier l'utilisateur) */
    public function deleteMap($idmap) {
        if (get_num($idmap) == 0)
            return false;
        //On ne peut pas modifier les maps officielles.
        if (get_data_in_db($this->mysqli, "maps_infos", "id", $idmap, "officielle") == 1)
            return false;
        mysqli_query_with_error($this->mysqli, "DELETE FROM maps_infos WHERE id=$idmap");
        mysqli_query_with_error($this->mysqli, "DELETE FROM maps_contenu WHERE id=$idmap");
        return unlink($_SERVER["DOCUMENT_ROOT"] . "/jeu/bibli/map/mima" . $idmap . ".jpg");
    }

    /** Udpate maps conquest preferences, which user_id = $idj. TODO : à protéger */
    public function updatePrefsMapConquete($idj, $prefmaps, $mdp) {
        if (get_num($idj) == 0 || $mdp != substr(get_data_in_db($this->mysqli, "gens", "user_id", $idj, "user_password"), 0, 20))
            return;
        $prefmaps = $this->mysqli->real_escape_string($prefmaps);
        mysqli_query_with_error($this->mysqli, "UPDATE gens SET prefs_maps_conquete='$prefmaps' WHERE user_id='$idj'");
    }

    /** Return a list of pack names, separate by "," (most light then array) */
    public function returnPPAutorise($idj, $mdp) {
        if (get_num($idj) == 0  || $mdp != substr(get_data_in_db($this->mysqli, "gens", "user_id", $idj, "user_password"), 0, 20))
            return "";
        $result = mysqli_query_with_error($this->mysqli, "SELECT nom_pack FROM pack_pourparlers_autorise WHERE id_joueur = '$idj'");
        $packs = "";
        while ($ligne = $result->fetch_assoc())
            $packs = $packs . "," . $ligne['nom_pack'];
        return $packs;
    }
    
     /** Return a tab with data of gamer, which user_id = $idj, and set gain posthunes and chahut points. TODO : Enregistrer les posthunes autrement, car là c'est pas ultra sécuritaire, et on gagne rien si on ferme le jeu avant la fenetre de fin de partie (ou dans certains cas de déco ?) M'enfin, c'est déjà ça.*/
    public function returnRewardsJoueur($idj, $id_game, $gain_posthunes, $mdp) {
        if (get_num($idj) == 0 || get_alphanum($id_game) == "" || ($gain_posthunes != 0 && get_num($gain_posthunes) <= 0) || $mdp != substr(get_data_in_db($this->mysqli, "gens", "user_id", $idj, "user_password"), 0, 20))
            return NULL;
        if($gain_posthunes > 250) {
            //TODO : changer le traitement de cette triche (notamment l'adresse mail, gmail ne doit pas nous considérer comme spam)
            mail("posthumanwar@gmail.com", "Tricherie dans PHW", "Un utilisateur tente d'avoir plus de 500 posthunes alors que c'est interdit ! (user_id = $idj, id_game = $id_game).");
            return; 
        }
        $date = strtotime("now");
        //On vérifie que les posthunes sont bien à 0. C'est une sécurité pour éviter qu'un hacker utilise la même partie pour gagner plusieurs fois des points. On interdit aussi les gains plus d'une heure après la partie.
        $result = mysqli_query_with_error($this->mysqli, "SELECT * FROM game_rewards WHERE id_joueur='$idj' AND id_game='$id_game' AND posthunes = 0 AND date > ($date-3600) LIMIT 1");
        if($result->num_rows == 0)
                return NULL;
        $rewards = $result->fetch_assoc();
        //On enregistre les posthunes gagnées
        mysqli_multi_query_with_error($this->mysqli, "UPDATE game_rewards SET posthunes = $gain_posthunes WHERE id_joueur='$idj' AND id_game='$id_game'; UPDATE gens SET posthunes = (posthunes + $gain_posthunes) WHERE user_id = $idj;");
        return $rewards;
    }
    
    public function returnVersionClient() {
        $result = mysqli_query_with_error($this->mysqli, "SELECT version_client FROM config_generale");
	$version = $result->fetch_assoc();
	return $version['version_client'];
    }

    public function mailAdmin($sujet, $mail) {
        $from = "ne-pas-repondre@posthumanwar.com";
        $to="gabwink@gmail.com";
        EnvoyerMail($sujet, $mail, $to, $from);
    }
}

?>
